#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h> // 包含sockaddr_in结构体和相关常量
#include <arpa/inet.h>  // 包含IP地址转换函数
#include <unistd.h>
class server
{
public:
    server(uint16_t port)
        : _listenfd(-1), _port(port)
    {
    }
    ~server()
    {
    }
    void MY_server(int sockfd)
    {
        while (1)
        {
            char buffer[1024];
            int n = read(sockfd, buffer, sizeof(buffer) - 1);
            if (n < 0)
            {
                std::cout << "read fail!" << std::endl;
                close(sockfd);
                break;
            }
            else if (n > 0)
            {
                buffer[n] = '0';
                std::cout << "client say:" << buffer << std::endl;
                std::string messager = "server echo# ";
                messager += buffer;
                write(sockfd, messager.c_str(), messager.size());
            }
            else
            {
                std::cout << "client exit me too!" << std::endl;
                close(sockfd);
                break;
            }
        }
    }
    void Insit()
    {
        int ret = socket(AF_INET, 0, SOCK_STREAM);
        if (ret < 0)
        {
            std::cout << "socket fail!" << std::endl;
            exit(1);
        }
        _listenfd = ret;
        struct sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_port = _port;
        local.sin_addr.s_addr = INADDR_ANY;
        socklen_t len = sizeof(local);
        int n = bind(_listenfd, (struct sockaddr *)&local, len);
        if (n > 0)
        {
            std::cout << "bind success!" << std::endl;
        }
        else
        {
            std::cout << "bind fail!" << std::endl;
            exit(2);
        }

        int s = listen(_listenfd, 5);
        if (s < 0)
        {
            std::cout << "listen fail!" << std::endl;
        }
    }
    void Start()
    {
        while (1)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = accept(_listenfd, (struct sockaddr *)&peer, &len);
            std::cout << "接收到一个客户端！" << std::endl;
            // 向客户端提供服务
            MY_server(sockfd);
        }
    }

private:
    int _listenfd;
    uint16_t _port;
};